const api = require('../../utils/api');
import lodashInit from "../../utils/lodashInit";
const lodash = require('lodash')

Component({
    lifetimes: {
        ready: function () {
            // 初始化数据到form中
            this.initForm()
            this.initAssign()
            // 初始化 pickerList 用 field 的 field 字段当key
            this.initPicker()
            this.setData({
                loadingTag: 1
            })
        }
    },
    properties: {
        /**
         * 单个字段数据结构
         *
         * title,
         * field,
         * value,
         * disable,
         * hide,
         * relyField(依赖某个其他的属性,当这个值等于value的时候显示),
         * relyValue(依赖某个其他的属性,当这个值等于value的时候显示),
         * type(input|selector|picker|tree|cascaderTree|time|date|search|picture)
         * inputType(number|password)
         * options([{label,value, children}]) （生效时机：type=select，picker, tree）
         * remoteOptions({url,param,method}) (请求数据选项的url，生效时机：同上）
         * remoteSearch（{url,param,method})(请求数据选项的url，生效时机：type=search）
         * searchField(查询的数据的那个属性，生效时机: type=search)
         * searchKey(查询数据的取哪个属性映射给value，: type=search)
         * searchResultKey(返回的数据value给那个filed字段，生效时机: type=search)
         * searchResultName(返回的数据的显示字段，生效时机: type=search)
         * pictureType(图片类型（common|assign）：type=picture)
         * assigns([{title}])
         *
         *
         *
         */
        fields: Array,
        title: {
            type: [String],
            default: '数据表单'
        },
        color: {
            type: [String],
            value: 'blue',
        },
        /**
         * 监听外部修改并且把效果填回表单
         */
        watchFields: Array,
    },
    data: {
        loadingTag: 0,
        // 一下map的key均为 fields 中 field
        // picker的选择集
        pickerMap: {},
        // 选择结果集
        pickerIndexMap: {},
        // 原始多选树数据
        multiPickerResourceTreeMap: {}, // 级联树结构为 "key":{deep:0,data:{传过来的原始树},title:'xxx,xxx,xxx'}
        // 原始多选树数据
        multiPickerIndexMap: {},
        // 查询的结果集
        searchResult: {},
        // 是否显示查询的结果集
        showSearchResult: {},
        // 模态框
        modalMap: {},
        // 文件map 文件路径集合
        fileMap: {},
        // 表单数据
        form: {},
        userId:wx.getStorageSync('userId')
    },
    observers: {
        'fields.**': function (v) {
            if (this.data.loadingTag) {
                this.watchFields()
            }
        }
    },
    methods: {
        watchFields() {
            let form = this.data.form
            let watchFields = this.properties.watchFields
            this.properties.fields.forEach((f) => {
                if (watchFields.indexOf(f.field) !== -1) {
                    if (f.type === 'input' || f.type === 'time' || f.type === 'date' || f.type === 'mutiInput') {
                        form[f.field] = f.value;
                        if (f.type === 'mutiInput' && f.value === undefined) {
                            form[f.field] = []
                        }
                    }
                    if (f.type === 'picture' && f.pictureType === 'assign') {
                        let fileMap = this.data.fileMap
                        if (!fileMap[f.field]) {
                            fileMap[f.field] = []
                        }
                        // 判断如果所有图片都没有值就进行初始化
                        let initFlag = true;
                        for (let file of fileMap[f.field]) {
                            if (file.path) {
                                initFlag = false;
                                break;
                            }
                        }
                        if (initFlag) {
                            fileMap[f.field] = f.assigns
                            this.setData({
                                fileMap
                            })
                        }
                        if (f.pictureType === 'assign' && initFlag) {
                            this.initAssign()
                        }
                    }
                    if (f.type === 'selector' || f.type === 'picker') {
                        const pickerIndexMap = this.data.pickerIndexMap
                        let pickerMap = this.data.pickerMap
                        // 更新picker选项
                        if (f.options && f.options.length > 0) {
                            pickerMap[f.field] = f.options
                            this.setData({
                                pickerMap
                            })
                        }
                        // 这里解析 value 值 为 index
                        if (f.value !== undefined) {
                            for (let i = 0; i < this.data.pickerMap[f.field].length; i++) {
                                if (this.data.pickerMap[f.field][i].value === f.value) {
                                    pickerIndexMap[f.field] = i
                                    // 重新设置对应的form的值
                                    form[f.field] = this.data.pickerMap[f.field][pickerIndexMap[f.field]].value
                                    break
                                }
                            }
                        } else {
                            pickerIndexMap[f.field] = undefined
                        }
                        this.setData({
                            pickerIndexMap
                        })
                    }
                    // todo 补充multiPicker的内容
                    if (f.type === 'cascaderTree' || f.type === 'tree') {
                        // 初始化赋值的代码
                        let multiPickerIndexMap = this.data.multiPickerIndexMap
                        let multiPickerResourceTreeMap = this.data.multiPickerResourceTreeMap
                        let deep = multiPickerResourceTreeMap[f.field]['deep']
                        // 如果原始级联树是空的，但field的options不是空的，则需要重新初始化
                        if (multiPickerResourceTreeMap[f.field].data && multiPickerResourceTreeMap[f.field].data.length === 0 && f.options && f.options.length > 0) {
                            this.initCascaderTree(f);
                        } else {
                            // 这里解析 value 值 为 index
                            if (f.value !== undefined) {
                                let values = f.value;
                                let currentNodeList = multiPickerResourceTreeMap[f.field].data;
                                for (let i = 0; i < values.length; i++) {
                                    if (!currentNodeList) {
                                        break;
                                    }
                                    for (let j = 0; j < currentNodeList.length; j++) {
                                        if (currentNodeList[j].value === values[i]) {
                                            multiPickerIndexMap[f.field][i] = j;
                                            currentNodeList = currentNodeList[j].children;
                                            break;
                                        }
                                    }
                                }
                            } else {
                                for (let i = 0; i < deep; i++) {
                                    multiPickerIndexMap[f.field][i] = 0 // 默认选中第一个
                                }
                            }
                            this.setData({
                                multiPickerIndexMap
                            })
                            // 重新计算范围数组
                            this.calcPickerMap(f.field)
                            // 更新form中的值
                            this.calcPickerForm(f.field)
                            // 重新计算用于显示的title
                            this.calcPickerTitle(f.field);
                        }
                    }
                }
            })
            this.setData({
                form
            })
        },
        initForm() {
            let form = {}
            this.properties.fields.forEach((f) => {
                form[f.field] = f.value;
            })
            this.setData({
                form
            })
        },
        /**
         * 父组件主动调用，用于回传form数据
         */
        voucherChange() {
            // console.log("父组件主动触发数据回传");
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        initPicker() {
            this.properties.fields.forEach((f) => {
                if (f.type === 'selector' || f.type === 'picker') {
                    let pickerMap = this.data.pickerMap
                    if (f.options) {
                        pickerMap[f.field] = f.options
                        this.setData({
                            pickerMap,
                        })
                    }
                    if (f.remoteOptions) {
                        let url = f.remoteOptions.url
                        let param = f.remoteOptions.param
                        let method = f.remoteOptions.method
                        if (method === 'post') {
                            api.post(url, param).then(res => {
                                pickerMap[f.field] = res.data
                                this.setData({
                                    pickerMap
                                })
                            })
                        }
                        if (method === 'get') {
                            api.get(url, {
                                param
                            }).then(res => {
                                pickerMap[f.field] = res.data
                                this.setData({
                                    pickerMap
                                })
                            })
                        }
                    }
                    const pickerIndexMap = this.data.pickerIndexMap
                    // 这里解析 value 值 为 index
                    if (f.value !== undefined) {
                        for (let i = 0; i < this.data.pickerMap[f.field].length; i++) {
                            if (this.data.pickerMap[f.field][i].value === f.value) {
                                pickerIndexMap[f.field] = i
                                break
                            }
                        }
                    } else {
                        pickerIndexMap[f.field] = undefined
                    }
                    this.setData({
                        pickerIndexMap
                    })
                }
                if (f.type === 'cascaderTree' || f.type === 'tree') {
                    this.initCascaderTree(f);
                }
            })
        },
        /**
         * 通过field初始化级联树
         * @param {field} f 
         */
        initCascaderTree(f) {
            const multiPickerResourceTreeMap = this.data.multiPickerResourceTreeMap
            let request;
            multiPickerResourceTreeMap[f.field] = {}
            if (f.options) {
                multiPickerResourceTreeMap[f.field]['data'] = f.options
            }
            if (f.remoteOptions) {
                let url = f.remoteOptions.url
                let param = f.remoteOptions.param
                let method = f.remoteOptions.method
                if (method === 'post') {
                    request = api.post(url, param)
                }
                if (method === 'get') {
                    request = api.get(url, {
                        param
                    })
                }
            }
            if (request) {
                request.then(res => {
                    if (res.code === 200) {
                        multiPickerResourceTreeMap[f.field]['data'] = res.data
                        if (multiPickerResourceTreeMap[f.field]['data']) {
                            this.initMutiPiker(multiPickerResourceTreeMap, f.field)
                        }
                    }
                })
            } else {
                if (multiPickerResourceTreeMap[f.field]['data']) {
                    this.initMutiPiker(multiPickerResourceTreeMap, f.field)
                }
            }
        },
        initAssign() {
            this.properties.fields.forEach((f) => {
                // 初始化图片列表，设置默认值
                if (f.type === 'picture') {
                    let fileMap = this.data.fileMap
                    fileMap[f.field] = []
                    if (f.value) {
                        if (f.value instanceof Array) {
                            fileMap[f.field] = [...f.value]
                        } else {
                            fileMap[f.field].push(f.value)
                        }
                    }
                    this.setData({
                        fileMap
                    })
                }
                if (f.type === 'picture' && f.pictureType === 'assign') {
                    let fileMap = this.data.fileMap
                    fileMap[f.field] = f.assigns
                    let value = f.value
                    // 如assigns中包含auto ture的字段，则自动填充一下
                    let autoAddAssignList = f.assigns.filter(assign => assign.autoAdd)
                    if (autoAddAssignList && value && autoAddAssignList.length > 0 && value.length > 0) {
                        // 将不会自动增加格子的数据补充进去
                        let filterValues = value.filter(v => {
                            let i = 0;
                            for (i; i < autoAddAssignList.length; i++) {
                                if (v.title.includes(autoAddAssignList[i].title)) {
                                    break;
                                }
                            }
                            if (i >= autoAddAssignList.length) {
                                return true;
                            } else {
                                return false;
                            }
                        });
                        if (filterValues && filterValues.length > 0) {
                            let aliasNamePictures = [] // 单独取出修改了名称的图片
                            filterValues.forEach(fv => {
                                let as = lodash.find(fileMap[f.field], {
                                    title: fv.title
                                })
                                if (as) {
                                    as['path'] = fv.path
                                    as['snowFlakeId'] = fv.snowFlakeId
                                    as['createBy'] = fv.createBy
                                } else {
                                    aliasNamePictures.push({
                                        ...fv,
                                        canEditTitle: true,
                                        needDelete: true,
                                    });
                                }
                            })
                            // 将修改了名称的图片，添加到第一个自增选项之前
                            if (aliasNamePictures.length > 0) {
                                let index = lodash.findIndex(fileMap[f.field], {
                                    autoAdd: true
                                });
                                fileMap[f.field].splice(index, 0, ...aliasNamePictures)
                            }
                        }

                        // 将会自动新增格子的数据添加好
                        let picMap = new Map();
                        autoAddAssignList.forEach(autoAddAssign => {
                            filterValues = value.filter(v => v.title.includes(autoAddAssign.title));
                            if (filterValues && filterValues.length > 0) {
                                picMap.set(autoAddAssign.title, []);
                                filterValues.forEach(v2 => {
                                    picMap.get(autoAddAssign.title).push({
                                        ...v2,
                                        needDelete: true,
                                        canEditTitle: true
                                    })
                                })
                            }
                        })
                        // 从fileMap中找到对应的数据titile的位置，在前面补充上去
                        if (picMap.size > 0) {
                            picMap.forEach((value, key) => {
                                let index = lodash.findIndex(fileMap[f.field], {
                                    title: key
                                });
                                // 设置自增选项的当前index
                                fileMap[f.field][index].index = value.length + 1
                                // 将数据添加到自增选项的前面
                                fileMap[f.field].splice(index, 0, ...value)
                            })
                        }
                    }

                    // 处理只能新增的图片，如果已有图片则加上禁止编辑的标记
                    f.assigns.forEach(item => {
                        if (item.onlyAdd && item.path && item.path.length > 0) {
                            if (item.createBy+''!== this.data.userId+'') {
                                item.disableEdit = true
                            }
                        }
                    })
                    // console.log("此时的assign");
                    // console.log(f.assigns);

                    this.setData({
                        fileMap
                    })
                }
            })
        },
        /**
         * 初始化多选级联树
         * @param {Object} multiPickerResourceTreeMap 组件中存储的原始多选picker树，每个field对应一个原始的传进来的 多选picker树  {field:[{label:'xx',value:'xx',children:[label...]},...],...}
         * @param {String} field form中对应的字段名 
         */
        initMutiPiker(multiPickerResourceTreeMap, field) {
            // 级联树初始化
            // 计算树的深度
            let deep = this.calcPickerDeep(multiPickerResourceTreeMap[field].data)
            multiPickerResourceTreeMap[field]['deep'] = deep
            // 初始化每列值
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            multiPickerIndexMap[field] = []
            let values = this.data.form[field];
            if (values && values.length > 0) { // 如果有传默认值就需要设置默认值
                let currentNodeList = multiPickerResourceTreeMap[field].data;
                for (let i = 0; i < values.length; i++) {
                    for (let j = 0; j < currentNodeList.length; j++) {
                        if (currentNodeList[j].value === values[i] || (typeof currentNodeList[j].value === 'string' && currentNodeList[j].value.toLowerCase() === values[i].toLowerCase())) {
                            multiPickerIndexMap[field][i] = j;
                            currentNodeList = currentNodeList[j].children;
                            break;
                        }
                    }
                }
            } else {
                for (let i = 0; i < deep; i++) {
                    multiPickerIndexMap[field][i] = 0 // 默认选中第一个
                }
            }
            this.setData({
                multiPickerResourceTreeMap,
                multiPickerIndexMap
            })
            this.calcMutiPickerAll(field)
        },
        /**
         * 计算树的深度
         * @param {List} multiPickerResourceTree 原始多选树数组 [{label:'xx',value:'xx',children:[label...]},...]
         */
        calcPickerDeep(multiPickerResourceTree) {
            if (multiPickerResourceTree) {
                let deep = 0;
                let num = 0; // 用于递归的临时深度
                function recursion(obj, k) { // 计算对象的深度
                    num = Math.max(num, k);
                    if (obj.children) {
                        obj.children.forEach(function (v, i) {
                            recursion(v, k + 1);
                        });
                    }
                }

                multiPickerResourceTree.forEach(item => { // 遍历找到最深的深度
                    recursion(item, 1);
                    if (num > deep) {
                        deep = num;
                    }
                    num = 0;
                });
                // console.log("树的深度为："+deep);
                return deep;
            }
        },
        /**
         * 计算级联树的范围数组【选择集】
         * @param {String} field 
         */
        calcPickerMap(field) {
            let indexs = this.data.multiPickerIndexMap[field]
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            let currentNodeList = this.data.multiPickerResourceTreeMap[field].data // 当前位置的原始数据列表
            let deep = this.data.multiPickerResourceTreeMap[field].deep
            let pickerMap = this.data.pickerMap
            pickerMap[field] = []
            multiPickerIndexMap[field] = [] // 会出现假如n级，某一列没有n级，只有n-1级，此时需要缩短列数组
            // 构建范围数组 & 重置选择列
            for (let i = 0; i < deep; i++) {
                if (currentNodeList.length > 0) {
                    pickerMap[field][i] = currentNodeList;
                    try {
                        if (indexs[i]) {
                            currentNodeList = currentNodeList[indexs[i]].children;
                            multiPickerIndexMap[field][i] = indexs[i];
                        } else {
                            currentNodeList = currentNodeList[0].children;
                            multiPickerIndexMap[field][i] = 0;
                        }
                    } catch (e) { // 数组越界异常说明后续没有值
                        continue;
                    }
                } else {
                    pickerMap[field][i] = []
                }
            }
            // 选择列补0，例如之前为三列，切换某一级后变成四列或更多列，就需要补0
            let count = 0;
            pickerMap[field].forEach(item => {
                if (item && item.length > 0) {
                    count++;
                }
            });
            let len = multiPickerIndexMap[field].length
            if (count > len) {
                for (let i = 0; i < count - len; i++) {
                    multiPickerIndexMap[field][len + i] = 0;
                }
            }
            this.setData({
                pickerMap: pickerMap,
                multiPickerIndexMap: multiPickerIndexMap
            })
        },
        /**
         * 计算 用于显示的title
         * @param {String} field 
         */
        calcPickerTitle(field) {
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            let pickerMap = this.data.pickerMap
            let columnNum = multiPickerIndexMap[field].length // 列长度
            let multiPickerResourceTreeMap = this.data.multiPickerResourceTreeMap
            multiPickerResourceTreeMap[field]['title'] = ""
            for (let i = 0; i < columnNum; i++) {
                if (pickerMap[field][i][multiPickerIndexMap[field][i]].label !== '不选择') {
                    multiPickerResourceTreeMap[field]['title'] += pickerMap[field][i][multiPickerIndexMap[field][i]].label + ","
                }
            }
            let length = multiPickerResourceTreeMap[field]['title'].length;
            if (length > 0) { // 去掉末尾的,
                multiPickerResourceTreeMap[field]['title'] = multiPickerResourceTreeMap[field]['title'].substring(0, length - 1)
            }
            this.setData({
                multiPickerResourceTreeMap
            });
        },
        /**
         * 计算 用于返回的form的值
         * @param {String} field 
         */
        calcPickerForm(field) {
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            let columnNum = this.data.multiPickerIndexMap[field].length
            let pickerMap = this.data.pickerMap
            let form = this.data.form
            form[field] = []
            for (let i = 0; i < columnNum; i++) {
                let node = pickerMap[field][i][multiPickerIndexMap[field][i]]
                if (node) {
                    form[field][i] = node.value
                } else { // 当出现节点为空的时候就不需要继续遍历了
                    break;
                }
            }
            this.setData({
                form
            })
        },
        /**
         * 重新计算各项多级树的值并返回
         * @param {String} field 
         */
        calcMutiPickerAll(field) {
            // 重新计算范围数组
            this.calcPickerMap(field)
            // 更新form中的值
            this.calcPickerForm(field)
            // 重新计算用于显示的title
            this.calcPickerTitle(field);
            // 调用父组件更新，传form
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 列选择改变时重新计算范围数组，并给父组件传值
         * @param {object} e 所绑定的组件回传的变化列 
         */
        columnchange(e) {
            const column = e.detail.column
            const value = e.detail.value
            const field = e.currentTarget.dataset.field
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            // 设置新的列的值
            multiPickerIndexMap[field][column] = value
            // 第c列的第v个数组
            // 1. 改变c列之后的列全部归零
            let columnNum = multiPickerIndexMap[field].length // 一共有多少列
            for (var i = 1; i <= columnNum - column - 1; i++) {
                multiPickerIndexMap[field][column + i] = 0;
            }
            this.setData({
                multiPickerIndexMap
            })
            // 重新计算多级树各个属性并返回
            this.calcMutiPickerAll(field)
        },
        /**
         * 单选择改变
         * @param e
         */
        pickerChange(e) {
            const field = e.currentTarget.dataset.field
            let pickerIndexMap = this.data.pickerIndexMap;
            pickerIndexMap[field] = parseInt(e.detail.value)
            let form = this.data.form
            form[field] = this.data.pickerMap[field][parseInt(e.detail.value)].value
            this.setData({
                form,
                pickerIndexMap
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 树形/多选 改变
         * @param e
         */
        pickerTreeChange(e) {
            const field = e.currentTarget.dataset.field
            if (!this.data.form[field]) { // 没值就用初始值，有值就用列更新值
                this.calcPickerForm(field)
            }
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 时间选择改变
         * @param e
         */
        pickerDateTimeChange(e) {
            const field = e.currentTarget.dataset.field
            let form = this.data.form
            form[field] = e.detail.value
            this.setData({
                form
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 输入改变
         * @param e
         */
        inputChange(e) {
            const field = e.currentTarget.dataset.field
            let form = this.data.form
            form[field] = e.detail.value
            this.setData({
                form,
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * switch开关改变
         * @param e
         */
        switchChange(e) {
            const field = e.currentTarget.dataset.field
            let form = this.data.form
            form[field] = e.detail.value
            this.setData({
                form,
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 复杂输入改变
         * @param e
         */
        mutiInputChange(e) {
            const field = e.currentTarget.dataset.field
            let form = this.data.form
            const index = e.currentTarget.dataset.index
            if (form[field] === undefined) {
                form[field] = [];
            }
            form[field][parseInt(index)] = e.detail.value
            this.setData({
                form,
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 搜索变更
         * @param e
         */
        searchChange(e) {
            const field = e.currentTarget.dataset.field
            const value = e.detail.value
            if (value !== undefined) {
                const url = e.currentTarget.dataset.url
                const method = e.currentTarget.dataset.method
                const searchField = e.currentTarget.dataset.searchfiled
                let param = e.currentTarget.dataset.param
                if (!param) {
                    param = {}
                }
                param[searchField] = value
                if (method === 'get') {
                    api.get(url, {
                        param
                    }).then(res => {
                        if (res.data && res.data.length) {
                            let searchResult = this.data.searchResult
                            let showSearchResult = this.data.showSearchResult
                            searchResult[field] = res.data
                            showSearchResult[field] = true
                            this.setData({
                                searchResult,
                                showSearchResult
                            })
                        }
                    })
                } else {
                    api.post(url, param).then(res => {
                        if (res.data && res.data.length) {
                            let searchResult = this.data.searchResult
                            let showSearchResult = this.data.showSearchResult
                            searchResult[field] = res.data
                            showSearchResult[field] = true
                            this.setData({
                                searchResult,
                                showSearchResult
                            })
                        }
                    })
                }
            } else {
                let searchResult = this.data.searchResult
                let showSearchResult = this.data.showSearchResult
                searchResult[field] = []
                showSearchResult[field] = false
                this.setData({
                    searchResult,
                    showSearchResult
                })
            }
        },
        /**
         * 选择某个搜索结果
         * @param e
         */
        resultChange(e) {
            let form = this.data.form
            const key = e.currentTarget.dataset.key
            const value = e.currentTarget.dataset.value
            const field = e.currentTarget.dataset.field
            const name = e.currentTarget.dataset.name

            form[field] = name
            form[key] = value

            let searchResult = this.data.searchResult
            let showSearchResult = this.data.showSearchResult
            searchResult[field] = []
            showSearchResult[field] = false

            this.setData({
                form,
                showSearchResult,
                searchResult
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 级联树/树改变
         * @param e
         */
        getChildren(e) {
            const column = e.detail.column
            const value = e.detail.value

            const field = e.currentTarget.dataset.field
            let pickerMap = this.data.pickerMap
            let multiPickerIndexMap = this.data.multiPickerIndexMap
            let multiPickerResourceTreeMap = this.data.multiPickerResourceTreeMap

            if (!multiPickerIndexMap[field]) {
                multiPickerIndexMap[field] = []
            }
            multiPickerIndexMap[field][column] = value

            // todo 将下一级加入到 pickerMap[field] 中
            this.setData({
                multiPickerIndexMap,
                pickerMap
            })
        },
        /**
         * 打开模态框
         * @param e
         */
        openModal(e) {
            // 判断是否允许上传图片
            const field = e.currentTarget.dataset.field
            const modalMap = this.data.modalMap
            if (!modalMap[field]) {
                modalMap[field] = true
            }
            modalMap[field] = true
            this.setData({
                modalMap
            })
        },
        /**
         * 关闭模态框
         * @param e
         */
        hideModal(e) {
            const field = e.currentTarget.dataset.field
            const modalMap = this.data.modalMap
            let form = this.data.form
            const file = this.data.fileMap[field]
            form[field] = file
            if (!modalMap[field]) {
                modalMap[field] = false
            }
            modalMap[field] = false
            this.setData({
                modalMap,
                form
            })
            this.triggerEvent('voucherChange', {
                form: this.data.form
            })
        },
        /**
         * 批量选择图片
         * @param e
         */
        nowUpload(e) {
            // 判断是否允许上传图片
            const disable = e.currentTarget.dataset.disable
            if (disable === undefined || !disable) {
                const that = this
                const sourceType = e.currentTarget.dataset.way
                const field = e.currentTarget.dataset.field
                let fileMap = this.data.fileMap
                if (!fileMap[field]) {
                    fileMap[field] = []
                }
                wx.chooseImage({
                    sourceType: [sourceType],
                    sizeType: ['original'],
                    count: 9,
                    success: res => {
                        if (res.errMsg === 'chooseImage:ok') {
                            for (const tempFilePath of res.tempFilePaths) {
                                fileMap[field].push({
                                    sourceType,
                                    path: tempFilePath
                                })
                            }
                            that.setData({
                                fileMap
                            })
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '请开启编辑！！',
                    icon: 'none',
                });
            }

        },
        /**
         * 编辑替换单个图片
         * @param e
         */
        editPicture(e) {
            // 判断是否允许进行图片操作
            const disable = e.currentTarget.dataset.disable
            if (disable === undefined || !disable) {
                const that = this
                const field = e.currentTarget.dataset.field
                const index = e.currentTarget.dataset.index
                let fileMap = this.data.fileMap
                wx.chooseImage({
                    sourceType: ['album', 'camera'],
                    sizeType: ['original'],
                    count: 1,
                    success: res => {
                        if (res.errMsg === 'chooseImage:ok') {
                            fileMap[field][index].path = res.tempFilePaths[0]
                            // 添加一个sourceType仅用于标识图片是重新添加的，不是从详情中取到的
                            fileMap[field][index].sourceType = 'album'
                            that.setData({
                                fileMap
                            })
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '请开启编辑！！',
                    icon: 'none',
                });
            }
        },
        /**
         * 查看图片
         * @param e
         */
        viewPicture(e) {
            const field = e.currentTarget.dataset.field
            const index = e.currentTarget.dataset.index
            const fileMap = this.data.fileMap[field]
            const urls = []
            fileMap.forEach(f => {
                if (f.path) {
                    urls.push(f.path)
                }
            })
            wx.previewImage({
                current: this.data.fileMap[field][index].path,
                urls,
            })
        },
        /**
         * 移除图片
         * @param e
         */
        removePicture(e) {
            const that = this
            // 判断是否允许进行图片操作
            const disable = e.currentTarget.dataset.disable
            if (disable === undefined || !disable) {
                wx.showModal({
                    title: '提示',
                    content: '确认要移除嘛？',
                    success(res) {
                        if (res.confirm) {
                            const field = e.currentTarget.dataset.field
                            const index = e.currentTarget.dataset.index
                            const fileMap = that.data.fileMap
                            fileMap[field].splice(fileMap[field].findIndex(e => e === fileMap[field][index]), 1)
                            that.setData({
                                fileMap
                            })
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '请开启编辑！！',
                    icon: 'none',
                });
            }
        },
        /**
         * 多一个选项去添加照片
         * @param e
         */
        addOrEditAssignPicture(e) {
            const that = this
            wx.showActionSheet({
                itemList: ['拍照', '从手机相册选择'],
                success: function (res) {
                    if (res.tapIndex === 0) {
                        that.addOrEditCameraAssignPicture(e)
                    }
                    if (res.tapIndex === 1) {
                        that.addOrEditAlbumAssignPicture(e)
                    }
                }
            })
        },
        /**
         * 添加订制格子的相册图片
         * @param e
         */
        addOrEditAlbumAssignPicture(e) {
            const that = this
            const field = e.currentTarget.dataset.field
            let title = e.currentTarget.dataset.title
            const index = e.currentTarget.dataset.index
            let fileMap = this.data.fileMap
            if (!fileMap[field]) {
                fileMap[field] = []
            }
            wx.chooseMedia({
                mediaType:['image'],
                sourceType: ['album'],
                sizeType: ['original'],
                count: 1,
                success: res => {
                    if (res.errMsg === 'chooseMedia:ok') {
                        // 如果是会自动新增格子的图片，则需要在当前位置之后追加一个格子
                        let current = fileMap[field][index];
                        let needDelete = false;
                        if (current && current.autoAdd) {
                            needDelete = true;
                            title = current.title + "-" + current.index
                            current.index = Number.parseInt(current.index) + 1
                            fileMap[field].splice(index, 0, {
                                ...current,
                            })
                        }
                        if (current.needDelete) {
                            needDelete = true;
                        }
                        // 这里加属性 传入的 assign 集合里的其他属性 如果有的话
                        fileMap[field][index] = {
                            title,
                            sourceType: 'album',
                            path: res.tempFiles[0].tempFilePath,
                            needDelete: needDelete, // 当删除图片时需要删除格子
                            canEditTitle: needDelete ? true : false,
                            index: current.index,
                        }
                        console.log(fileMap[field][index] );
                        that.setData({
                            fileMap
                        })
                    }
                }
            })
        },
        /**
         * 添加订制格子的相机图片
         * @param e
         */
        addOrEditCameraAssignPicture(e) {
            const that = this
            const field = e.currentTarget.dataset.field
            let title = e.currentTarget.dataset.title
            const index = e.currentTarget.dataset.index
            let fileMap = this.data.fileMap
            if (!fileMap[field]) {
                fileMap[field] = []
            }
            wx.chooseImage({
                sourceType: ['camera'],
                sizeType: ['original'],
                count: 1,
                success: res => {
                    if (res.errMsg === 'chooseImage:ok') {
                        // 如果是会自动新增格子的图片，则需要在当前位置之后追加一个格子
                        let current = fileMap[field][index];
                        let needDelete = false;
                        if (current && current.autoAdd) {
                            title = current.title + "-" + current.index
                            needDelete = true;
                            current.index = Number.parseInt(current.index) + 1
                            fileMap[field].splice(index, 0, {
                                ...current,
                            })
                        }
                        if (current.needDelete) {
                            needDelete = true;
                        }
                        // 这里加属性 传入的 assign 集合里的其他属性 如果有的话
                        fileMap[field][index] = {
                            title,
                            sourceType: 'camera',
                            path: res.tempFilePaths[0],
                            needDelete: needDelete, // 当删除图片时需要删除格子
                            canEditTitle: needDelete ? true : false,
                            index: current.index
                        }
                        that.setData({
                            fileMap
                        })
                    }
                }
            })
        },
        /**
         * 查看订制格子的图片
         * @param e
         */
        viewAssignPicture(e) {
            const field = e.currentTarget.dataset.field
            const index = e.currentTarget.dataset.index
            const fileMap = this.data.fileMap[field]
            const urls = []
            fileMap.forEach(f => {
                if (f.path) {
                    urls.push(f.path)
                }
            })
            wx.previewImage({
                current: this.data.fileMap[field][index].path,
                urls,
            })
        },
        /**
         * 移除订制格子的图片
         * @param e
         */
        removeAssignPicture(e) {
            const that = this

            wx.showModal({
                title: '提示',
                content: '确认要移除嘛？',
                success(res) {
                    if (res.confirm) {
                        const field = e.currentTarget.dataset.field
                        const index = e.currentTarget.dataset.index
                        const fileMap = that.data.fileMap
                        if (fileMap[field][index].needDelete) { // 判断是否需要删除整个格子
                            fileMap[field].splice(index, 1)
                        } else {
                            delete fileMap[field][index].path
                        }
                        that.setData({
                            fileMap
                        })
                    }
                }
            })
        },
        /**
         * 修改图片名称
         */
        editPictureTitle(e) {
            const title = e.detail.value
            const field = e.currentTarget.dataset.field
            const index = e.currentTarget.dataset.index
            const fileMap = this.data.fileMap
            if (title && title.length > 0) {
                fileMap[field][index].title = title
                this.setData({
                    fileMap
                })
            }
        },
        /**
         * 标题点击事件
         */
        titleClick(e) {
            let methodName = e.currentTarget.dataset.method
            if (methodName) { // 调用父组件的事件
                this.triggerEvent(methodName)
            }
        }
    }
});